import db from '../lib/db';
import { PERMISSION_LEVEL } from '../middlewares/auth/rowLevelPermission';

/**
 * 检查用户是否有权限访问特定数据
 * @param userId 用户ID
 * @param entityType 实体类型
 * @param entityId 实体ID
 * @param permissionLevel 所需权限级别
 */
export async function checkUserHasPermission(
  userId: string,
  entityType: string,
  entityId: string,
  permissionLevel: number = PERMISSION_LEVEL.READ
): Promise<{ hasPermission: boolean; reason?: string }> {
  try {
    // 首先检查实体是否存在
    const model = db[entityType];
    const entityExists = await model.findFirst({
      where: {
        id: entityId
      },
      select: { id: true, creator: true }
    });
    
    if (!entityExists) {
      return { hasPermission: false, reason: `实体不存在: ${entityId}` };
    }
    
    // 检查是否是创建者
    if (entityExists.creator === userId) {
      return { hasPermission: true };
    }
    
    // 检查是否有授权
    const hasAuthorization = await db.data_access_authorization.findFirst({
      where: {
        entity_id: entityId,
        entity_type: entityType,
        user_id: userId,
        permission: { gte: permissionLevel },
        deleted_at: null
      },
      select: { id: true }
    });
    
    if (hasAuthorization) {
      return { hasPermission: true };
    }
    
    // 没有权限的具体原因
    const permissionLevelText = {
      [PERMISSION_LEVEL.READ]: '读取',
      [PERMISSION_LEVEL.WRITE]: '修改',
      [PERMISSION_LEVEL.AUTHORIZE]: '授权'
    }[permissionLevel] || '访问';
    
    return {
      hasPermission: false,
      reason: `您没有${permissionLevelText}此数据的权限`
    };
  } catch (e) {
    console.error(e);
    return { hasPermission: false, reason: '权限检查过程中发生错误' };
  }
}

/**
 * 为数据库查询生成行级权限过滤条件
 */
export function generateRowLevelPermissionFilter(userId: string, entityType: string) {
  // 注意：这里不能使用关系字段，而是返回一个简单的creator条件
  // 完整的权限检查会在checkUserHasPermission函数中完成
  // 或者在服务层通过显式查询data_access_authorization表来实现
  return {
    creator: userId
  };
}

/**
 * 为服务层提供的完整行级权限过滤实现
 * 此函数可以在服务层直接调用，返回当前用户有权访问的实体ID列表
 */
export async function getUserAuthorizedDataIds(userId: string, entityType: string, permissionLevel: number = PERMISSION_LEVEL.READ): Promise<string[]> {
  try {
    // 查询当前用户被授权访问的实体ID
    const authorizations = await db.data_access_authorization.findMany({
      where: {
        user_id: userId,
        entity_type: entityType,
        permission: { gte: permissionLevel },
        deleted_at: null
      },
      select: { entity_id: true }
    });
    
    // 提取实体ID列表
    const authorizedIds = authorizations.map(auth => auth.entity_id);
    
    return authorizedIds;
  } catch (e) {
    console.error(e);
    return [];
  }
}